package cn._2dland.net
{
	import cn._2dland.utils.VideoUtils;
	import cn._2dland.video.StreamInfo;
	
	import flash.events.Event;
	import flash.net.URLRequest;

	public class TudouPartLoader extends PartLoader
	{
		/** 土豆API地址 */
		public static const TUDOU_URL:String = "http://v2.tudou.com/v2/cdn?safekey=ShuZiQiuGuoZhao&id=";
		/** 最大BRT值 */
		public static const MAX_BRT:int = 4;

		public function TudouPartLoader() {
			super();
		}

		override public function load(partXml:XML):void {
			super.load(partXml);

			var url:String = TUDOU_URL + partXml.vid + "&noCache=" + Math.ceil(Math.random() * 10000);
			_loader.load(new URLRequest(url));
		}

		override protected function loadCompleteHandler(e:Event):void {
			var tudouXml:XML = new XML(_loader.data);

			if(tudouXml == null) {
				_infos.push(new StreamInfo(VideoUtils.DEFAULT_NAME, VideoUtils.DEFAULT_URL, VideoUtils.DEFAULT_DURATION));
			} else {
				var brt:int = 0;
				var videoUrl:String = null;
				// 获取所有f节点
				var fs:XMLList = tudouXml.elements("*").elements("f");
				// 查找出brt值最大的节点
				for(var i:int=0; i<fs.length(); i++) {
					var fbrt:int = int(fs[i].@brt);

					if(fbrt == MAX_BRT) {
						videoUrl = fs[i].toString();
						break;
					} else if(fbrt > brt) {
						brt = fbrt;
						videoUrl = fs[i].toString();
					}
				}

				_infos.push(new StreamInfo(_partName, videoUrl, tudouXml.@time, _smooth));
			}
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		/**
		 * 
		 * @param root
		 * @return 
		 * 
		 */		
		private function findClearVideo(root:XML):String {
			// 存储最大的brt值
			var brt:int = 0;
			var videoUrl:String = null;

			var fs:XMLList = root.a.f;
			for(var i:int=0; i<fs.length(); i++){
				if(fs[i].@brt == MAX_BRT){
					videoUrl = fs[i].toString();
					return videoUrl;
				} else if(fs[i].@brt > brt) {
					brt = int(fs[i].@brt);
					videoUrl = fs[i].toString();
				}
			}
			
			return null;
		}
	}
}